#include <iostream>  
#include <queue>  
#include <algorithm>  
using namespace std;  
  
struct Node  
{  
    Node *pLeft;  
    Node *pRight;  
    int data;  
};  
  
void Link(Node *nodes, int parent, int left, int right);  
void PrintNodeByLevel(Node *root);  
  
int main()
{  
    Node test1[9] = {0};  
    int i;  
  
    for (i = 0; i < 9; i++)   
    {  
        test1[i].data = i;  
    }  
  
    Link(test1, 1, 2, 3);  
    Link(test1, 2, 4, 5);  
    Link(test1, 3, -1, 6);  
    Link(test1, 5, 7, 8);  
  
    PrintNodeByLevel(&test1[1]);  
  
    return 0;  
}  
  
void Link(Node *nodes, int parent, int left, int right)  
{  
    if (left != -1)   
    {  
        nodes[parent].pLeft = &nodes[left];  
    }  
    if (right != -1)   
    {  
        nodes[parent].pRight = &nodes[right];  
    }  
}  
  
void PrintNodeByLevel(Node *root)  
{  
    int parentSize = 1, childSize = 0;  
    Node * temp;  
    queue<Node *> q;  
    q.push(root);  
    do  
    {  
        temp = q.front();         
        cout << temp->data << "  ";  
        q.pop();  
  
        if (temp->pLeft != NULL)   
        {  
            q.push(temp->pLeft);  
            childSize ++;  
        }  
        if (temp->pRight != NULL)   
        {  
            q.push(temp->pRight);  
            childSize ++;  
        }  
  
        parentSize--;  
        if (parentSize == 0)   
        {  
            parentSize = childSize;  
            childSize = 0;  
            cout << endl;  
        }  
  
    } while (!q.empty());  
}  
